package it.CookBook;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Demonstrates expandable lists using a custom {@link ExpandableListAdapter}
 * from {@link BaseExpandableListAdapter}.
 */
public class CookBookActivity extends ExpandableListActivity{

	ExpandableListAdapter mAdapter;

	String cookBookRoot = "/mnt/sdcard/Ricettario";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set up our adapter
		mAdapter = new MyExpandableListAdapter();
		setListAdapter(mAdapter);
		registerForContextMenu(getExpandableListView());
	}

	// @Override
	// public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
	// menuInfo) {
	// menu.setHeaderTitle("Sample menu");
	// menu.add(0, 0, 0, R.string.expandable_list_sample_action);
	// }

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item
				.getMenuInfo();

		String title = ((TextView) info.targetView).getText().toString();

		int type = ExpandableListView
				.getPackedPositionType(info.packedPosition);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			int groupPos = ExpandableListView
					.getPackedPositionGroup(info.packedPosition);
			int childPos = ExpandableListView
					.getPackedPositionChild(info.packedPosition);
			Toast.makeText(
					this,
					title + ": Child " + childPos + " clicked in group "
							+ groupPos, Toast.LENGTH_SHORT).show();
			return true;
		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			int groupPos = ExpandableListView
					.getPackedPositionGroup(info.packedPosition);
			Toast.makeText(this, title + ": Group " + groupPos + " clicked",
					Toast.LENGTH_SHORT).show();
			return true;
		}

		return false;
	}

	/**
	 * A simple adapter which maintains an ArrayList of photo resource Ids. Each
	 * photo is displayed as an image. This adapter supports clearing the list
	 * of photos and adding a new photo.
	 */
	public class MyExpandableListAdapter extends BaseExpandableListAdapter {
		// Sample data set. children[i] contains the children (String[]) for
		// groups[i].
//		private String[] groups = { "Category1", "Category2", "Category3",
//				"Category4" };
//		private String[][] children = {
//				{ "Charity1", "Charity2", "Charity3", "Charity4" },
//				{ "Charity5", "Charity6", "Charity7", "Charity8" },
//				{ "Charity9", "Charity10" }, { "Charity11", "Charity12" } };

		public MyExpandableListAdapter() {
			ArrayList<String> category = new ArrayList<String>();
			ArrayList<ArrayList<NodeBean>> book = new ArrayList<ArrayList<NodeBean>>();

			File directory = new File(cookBookRoot);
			createNodes(directory, new ArrayList<String>(), category, book);
			setGroups(category);
			setChildren(book);
		}
		private ArrayList<String> groups;
		
		private ArrayList<ArrayList<NodeBean>> children;
		
		public void setGroups(ArrayList<String> groups) {
			this.groups = groups;
		}

		public void setChildren(ArrayList<ArrayList<NodeBean>> children) {
			this.children = children;
		}

		public Object getChild(int groupPosition, int childPosition) {
			return children.get(groupPosition).get(childPosition).getName();
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		public int getChildrenCount(int groupPosition) {
			return children.get(groupPosition).size();
		}

		public TextView getGenericView() {
			// Layout parameters for the ExpandableListView
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT, 64);

			TextView textView = new TextView(CookBookActivity.this);
			textView.setLayoutParams(lp);
			// Center the text vertically
			textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			// Set the text starting position
			textView.setPadding(36, 0, 0, 0);
			return textView;
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			TextView textView = getGenericView();
			textView.setText(getChild(groupPosition, childPosition).toString());
			return textView;
		}

		public Object getGroup(int groupPosition) {
			return groups.get(groupPosition);
		}

		public int getGroupCount() {
			return groups.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			TextView textView = getGenericView();
			textView.setText(getGroup(groupPosition).toString());
			return textView;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		public boolean hasStableIds() {
			return true;
		}
	}

	private void createNodes(File fileIn, ArrayList<String> top, ArrayList<String> category, ArrayList<ArrayList<NodeBean>> book) {
		if (!fileIn.exists())
			return;
		FilenameFilter filenameFilter = new FilenameFilter() {

			public boolean accept(File dir, String name) {
				if (name.endsWith(".db"))
					return false;
				return true;
			}
		};
		File[] files = dirListByAscendingName(fileIn, filenameFilter);

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				File[] filestemp = dirListByAscendingName(files[i], filenameFilter);
				if (filestemp!= null && allImagesAreFake(filestemp) == true)
				{
					ArrayList<NodeBean> arrayTmp = new ArrayList<NodeBean>();
					for (int jk = 0; jk < filestemp.length; jk++) {
						String name = files[i].getName();
						if (filestemp.length > 1)
							name = name + " ("+(jk+1)+ ")";
						System.out.println("################"+filestemp[jk].getName()+" renaming in ->"+name);
						arrayTmp.add(new NodeBean(filestemp[jk],name.toLowerCase()));
					}
					book.add(arrayTmp);
					
				}
				else
				{
					System.out.println("DIR = " + files[i].getName());
//					category = new DefaultMutableTreeNode(new NodeBean(files[i], files[i].getName()));
					category.add(files[i].getName());
					createNodes(files[i], top, category, book);
				}
			} else if (files[i].isFile()) {
				String fileName = files[i].getName();
				System.out.println("Ricetta = " + fileName);
				if (fileName.toLowerCase().startsWith("image") && fileIn.isDirectory())
					fileName = fileIn.getName();
//				book = new DefaultMutableTreeNode(new NodeBean(files[i], fileName));
				ArrayList<NodeBean> arrayTmp = new ArrayList<NodeBean>();
				arrayTmp.add(new NodeBean(files[i], fileName));
				book.add(arrayTmp);
				//top.add(book);
			}
		}

	}

	@SuppressWarnings("unchecked")
	public static File[] dirListByAscendingName(File folder,
			FilenameFilter filenameFilter) {
		if (!folder.isDirectory()) {
			return null;
		}
		File files[] = folder.listFiles(filenameFilter);
		Arrays.sort(files, new Comparator() {
			public int compare(final Object o1, final Object o2) {
				return new String(((File) o1).getName().toLowerCase()).compareTo(new String(((File) o2).getName().toLowerCase()));
			}
		});
		return files;
	}

	private boolean allImagesAreFake(File[] files) {
		boolean returnValue = true;
		for (int i = 0; i < files.length; i++) {
			if (!files[i].getName().toLowerCase().startsWith("image") && !files[i].getName().toLowerCase().startsWith("001"))
				returnValue = false;
		}
		return returnValue;
	}
}